import React, { useState, useEffect, Fragment } from 'react';
import { connect } from 'umi';
import { message, Cascader } from 'antd';

const SelectRegion = (props: {
  dispatch?: any;
  onChange?: (checkedList: any[]) => void;
  value?: any;
  disabled?: boolean;
}) => {
  const { dispatch, disabled, value } = props;

  // 是否加载完成
  const [isLoaded, setIsLoaded] = useState(false);

  // 地区列表
  const [optionArea, setOptionArea] = useState<any>([]);

  // 初始进来加载一次
  useEffect(() => {
    getAreaList(null);
  }, []);

  // 如果有默认值再重新加载一次
  useEffect(() => {
    if (value && !isLoaded) {
      console.log(value);
      setIsLoaded(true);
      getAreaList(value);
    }
  }, [value]);

  // 地区数据处理
  const areaFm = (data: any) => {
    let arr: any = [];
    if (data && data.length) {
      data.forEach((item: any) => {
        item.value = item.id;
        item.label = item.areaName;
        item.isLeaf = !item.childCount;
        let children = item.children;
        if (children) {
          children = areaFm(children);
        }
        // arr.push({ label: item.areaName, value: item.id, isLeaf: !item.childCount, });
        arr.push(item);
      });
    }
    return arr;
  };

  // 编辑回显处理，根据末级id查询该id的完整tree
  const getAreaTree = (id: any) => {
    let arr: any = [];
    return new Promise((proRes: any) => {
      dispatch({
        type: 'common/getAreaTree',
        payload: { id },
        callback: (res: any) => {
          const { code, data, msg } = res;
          if (code === 1) {
            arr = areaFm(data.children);
          } else {
            message.error(msg || '服务器开小差了~');
          }
          proRes(arr);
        },
      });
    });
  };

  // 获取地区
  const getAreaList = (value: any) => {
    dispatch({
      type: 'common/getAreaListByPid',
      payload: { pid: 0 },
      callback: async (res: any) => {
        const { code, data, msg } = res;
        if (code === 1) {
          let arr = areaFm(data);
          if (value && value.length > 1) {
            // 地区第一级
            let firstStage = value[0];
            // 地区末级
            let lastStage = value[value.length - 1];
            let childArr = await getAreaTree(lastStage);
            if (arr && arr.length > 0) {
              for (let i = 0; i < arr.length; i++) {
                if (arr[i].id == firstStage) {
                  arr[i].children = childArr;
                  break;
                }
              }
            }
          }
          setOptionArea(arr);
        } else {
          message.error(msg || '服务器开小差了~');
        }
      },
    });
  };

  // 地区选择
  const areaChange = (value: any, selectedOptions: any) => {
    // 加载完成
    setIsLoaded(true);
    // value 返回值是一个数组
    props.onChange?.(value);
  };

  // 地区加载
  const loadData = async (selectedOptions: any) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    dispatch({
      type: 'common/getAreaListByPid',
      payload: { pid: selectedOptions.pop().value },
      callback: (res: any) => {
        targetOption.loading = false;
        const { code, data, msg } = res;
        if (code === 1) {
          targetOption.children = areaFm(data);
          setOptionArea([...optionArea]);
        } else {
          message.error(msg || '服务器开小差了~');
        }
      },
    });
  };

  return (
    <Cascader
      value={value}
      options={optionArea}
      loadData={loadData}
      onChange={areaChange}
      changeOnSelect
      disabled={disabled}
    />
  );
};
export default connect()(SelectRegion);
